package com.chunxuan.langquan.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatEditText;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.chunxuan.langquan.R;
import com.chunxuan.langquan.base.Base2Activity;
import com.chunxuan.langquan.base.BaseResult2;
import com.chunxuan.langquan.dao.bean.WxUserInfo1;
import com.chunxuan.langquan.dao.http.APIRetrofit;
import com.chunxuan.langquan.support.util.ActiviceCollector;
import com.chunxuan.langquan.support.util.Logg;
import com.chunxuan.langquan.ui.listener.MyOrientationListener;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.util.HandlerUtil;
import com.ruitu.arad.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class RegistActivity extends Base2Activity implements HandlerUtil.OnReceiveMessageListener{
    private AppCompatEditText et_phone, et_code, et_pwd,et_confirm_pwd;// 手机号，验证码，密码,确认密码
    private TextView tv_send_code, tv_ok, tv_privacy_policy, tv_service_agreement;// 发送验证码,注册，隐私政策，协议条款
//    private CheckBox cb_check;
//
    private int LOGIN_TYPE = 0;// 0 普通登录 1 微信登录
    private WxUserInfo1 wxUserInfo;// 微信登录后解析的微信用户对象


    //百度地图-获取定位
    private LocationClient mylocationClient;//定位服务客户对象
    private MylocationListener mylistener;//重写的监听类
    private Context context;
    private MyOrientationListener myOrientationListener;//方向感应器类对象
    private int count=0;

    private String phone, code, pwd,confirmPwd;
    private boolean isCd = false;// 是否正在倒计时
    private int currSecond = 60;// 当前倒计时的秒数
//
    private HandlerUtil.HandlerHolder handler = new HandlerUtil.HandlerHolder(this);

    @Override
    public void handlerMessage(Message msg) {
        if (msg.what == 20101951) {
            currSecond--;
            if (currSecond <= 0) {
                tv_send_code.setText("获取验证码");
                currSecond = 60;
                isCd = false;// 取消倒计时状态
            } else {
                tv_send_code.setText(currSecond + "秒");
                handler.sendEmptyMessageDelayed(20101951, 1000);
            }
        }
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_regist;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActiviceCollector.addActivity(this);
        List<String> permissionList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (!permissionList.isEmpty()) {
            String[] permissions = permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(this, permissions, 1);
        }
        this.context = this;
        initLocation();
        et_phone = findViewById(R.id.et_1);
        et_code = findViewById(R.id.et_2);
        et_pwd = findViewById(R.id.et_3);
        et_confirm_pwd=findViewById(R.id.et4);
        tv_send_code = findViewById(R.id.tv_send_sms);
        tv_privacy_policy = findViewById(R.id.tv_privacy_policy);
        tv_service_agreement = findViewById(R.id.tv_service_agreement);
        tv_ok = findViewById(R.id.tv_ok);
//        cb_check = findViewById(R.id.cb_check);
        setHeadTitle("");
        setOnClickListener(tv_send_code, tv_ok, tv_privacy_policy, tv_service_agreement);
    }
    private void initLocation() {
        //定位服务的客户端。宿主程序在客户端声明此类，并调用，目前只支持在主线程中启动
        mylocationClient = new LocationClient(this);
        mylistener = new MylocationListener();

        //注册监听器
        mylocationClient.registerLocationListener(mylistener);
        //配置定位SDK各配置参数，比如定位模式、定位时间间隔、坐标系类型等
        LocationClientOption mOption = new LocationClientOption();
        //设置坐标类型
        mOption.setCoorType("bd09ll");
        //设置是否需要地址信息，默认为无地址
        mOption.setIsNeedAddress(true);
        //设置是否打开gps进行定位
        mOption.setOpenGps(true);
        //设置扫描间隔，单位是毫秒 当<1000(1s)时，定时定位无效
        int span = 2000;
        mOption.setScanSpan(span);
        //设置 LocationClientOption
        mylocationClient.setLocOption(mOption);

        myOrientationListener = new MyOrientationListener(context);
    }
    /*
     *定位请求回调接口
     */
    public class MylocationListener implements BDLocationListener {
        //定位请求回调函数,这里面会得到定位信息
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            //BDLocation 回调的百度坐标类，内部封装了如经纬度、半径等属性信息
            //MyLocationData 定位数据,定位数据建造器
            /*
             * 可以通过BDLocation配置如下参数
             * 1.accuracy 定位精度
             * 2.latitude 百度纬度坐标
             * 3.longitude 百度经度坐标
             * 4.satellitesNum GPS定位时卫星数目 getSatelliteNumber() gps定位结果时，获取gps锁定用的卫星数
             * 5.speed GPS定位时速度 getSpeed()获取速度，仅gps定位结果时有速度信息，单位公里/小时，默认值0.0f
             * 6.direction GPS定位时方向角度
             * */
            count++;
            Log.e("==位置==",bdLocation.getProvince()+"-"+bdLocation.getCity()+"-"+bdLocation.getDistrict()+"-"+bdLocation.getStreet());
            if(null!=bdLocation.getCity()){
                String city=Arad.preferences.getString("cityInfo");
                if(TextUtils.isEmpty(city)){
                    Logg.e("==获取城市-保存城市===");
                    Arad.preferences.putString("cityInfo", bdLocation.getCity()).flush();
                }
                if(!city.equals(bdLocation.getCity())){
                    Arad.preferences.putString("cityInfo", bdLocation.getCity()).flush();
                }
            }
        }
    }

    /*
     *定位服务的生命周期，达到节省
     */
    @Override
    protected void onStart() {
        super.onStart();
        //开启定位，显示位置图标
        if(!mylocationClient.isStarted()){
            mylocationClient.start();
        }
        myOrientationListener.start();
    }
    @Override
    protected void onStop() {
        super.onStop();
        mylocationClient.stop();
        myOrientationListener.stop();
    }
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.tv_send_sms:
                if (!isCd) {
                    phone = et_phone.getText().toString().trim();
                    if (TextUtils.isEmpty(phone)) {
                        ToastUtils.showShort("请输入手机号");
                        return;
                    }
                    getMsgCode();
                    showProgress();
                    isCd = true;
                    handler.sendEmptyMessage(20101951);
                }
                break;
            case R.id.tv_ok:
//                Intent intent=new Intent(this, SelectCityActivity.class);
//                startActivity(intent);
//                if (!cb_check.isChecked()) {
//                    ToastUtils.showShort("请阅读并同意《用户服务协议》");
//                    return;
//                }
                phone = et_phone.getText().toString().trim();
                code = et_code.getText().toString().trim();
                pwd = et_pwd.getText().toString().trim();
                confirmPwd=et_confirm_pwd.getText().toString().trim();
                if (TextUtils.isEmpty(phone)) {
                    ToastUtils.showShort("请输入手机号");
                    return;
                }
                if (TextUtils.isEmpty(code)) {
                    ToastUtils.showShort("请输入验证码");
                    return;
                }
                if (TextUtils.isEmpty(pwd)) {
                    ToastUtils.showShort("请输入密码");
                    return;
                }
                if (TextUtils.isEmpty(confirmPwd)) {
                    ToastUtils.showShort("请再次输入密码");
                    return;
                }
                register();
                showProgress();
                break;
            case R.id.tv_privacy_policy:

                break;
            case R.id.tv_service_agreement:

                break;
        }
//        if (v == tv_1) {// 阅读用户协议
//            cb_check.setChecked(!cb_check.isChecked());
//        }
////        if (v == tv_2) {
////            startActivity(UserAgreeActivity.class);
////        }
////        if (v == tv_privacy) {
////            startActivity(PrivacyAgreeActivity.class);
////        }
//        if (v == tv_send_code) {
//            if (!isCd) {
//                phone = et_phone.getText().toString().trim();
//                if (TextUtils.isEmpty(phone)) {
//                    ToastUtils.showShort("请输入手机号");
//                    return;
//                }
////                getMsgCode();
//                showProgress();
//                isCd = true;
//                handler.sendEmptyMessage(20101951);
//            }
//        }
//        if (v == tv_ok) {
//            if (!cb_check.isChecked()) {
//                ToastUtils.showShort("请阅读并同意《用户服务协议》");
//                return;
//            }
//            phone = et_phone.getText().toString().trim();
//            code = et_code.getText().toString().trim();
//            pwd = et_pwd.getText().toString().trim();
//            if (TextUtils.isEmpty(phone)) {
//                ToastUtils.showShort("请输入手机号");
//                return;
//            }
//            if (TextUtils.isEmpty(code)) {
//                ToastUtils.showShort("请输入验证码");
//                return;
//            }
//            if (TextUtils.isEmpty(pwd)) {
//                ToastUtils.showShort("请输入密码");
//                return;
//            }
////            register();
//            showProgress();
//        }
    }

    public Disposable getMsgCode() {
        return APIRetrofit.getDefault().getMsgCode(phone,"register")
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        Logg.e("==发送短信验证码== " + baseResult2);
                        if (baseResult2.isSuccess()) {
                            ToastUtils.showShort(baseResult2.getMsg());
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("发送失败，请重试");
                    }
                });
    }

    public Disposable register() {
        return APIRetrofit.getDefault().register(phone, pwd,confirmPwd,code)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        Logg.e("==注册账号== " + baseResult2);
                        if (baseResult2.isSuccess()) {
                            ToastUtils.showShort(baseResult2.getMsg());
                            finish();
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
//                            if (TextUtils.equals("4001", baseResult2.getCode())) {// 注册成功,完善信息
//                                LinkedTreeMap<String, Integer> user = (LinkedTreeMap) baseResult2.getData();
//                                String tmp = user.get("id") + "";
//                                if (tmp.contains(".")) {
//                                    Global.USER_ID = tmp.substring(0, tmp.lastIndexOf("."));
//                                } else {
//                                    Global.USER_ID = tmp;
//                                }
//                                Logg.i("Global.USER_ID = " + Global.USER_ID);
//                                startActivity(RealAuthAgentActivity.class);
//                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("注册失败，请重试");
                    }
                });
    }

}
